package com.tjh.springbootapi.webSocket.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tjh.springbootapi.webSocket.ChannelSupervise;
import com.tjh.springbootapi.webSocket.utils.StrUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Objects;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

/**
 * Create by koala on 2022-08-14
 */
@Slf4j
public class NioWebSocketHandler extends SimpleChannelInboundHandler<Object> {

    private WebSocketServerHandshaker handshaker;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("收到消息：{}", Objects.nonNull(msg) ? msg.toString() : "");
        if (msg instanceof FullHttpRequest) {
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        log.info("客户端加入连接：" + ctx.channel());
        ChannelSupervise.cacheChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        log.info("客户端断开连接：" + ctx.channel());
        ChannelSupervise.removeChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 判断是否是有效连接
        if (!ChannelSupervise.ChannelMap.containsKey(ctx.channel().id().asShortText())) {
            log.info("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException("no login!");
        }

        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            log.info("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        // 返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
        log.info("接收到消息：{}", request);
    }

    /**
     * 唯一的一次http请求，用于创建websocket
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            log.error("若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端");
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }

        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:5255/websocket", null, false);
        String uri = req.uri();
        String socketKey = null;
        String businessSocketKey = null;
        String userId = null;
        JSONObject wsApiInfo = null;
        if (uri.contains("?")) {
            try {
                uri = URLDecoder.decode(uri, "UTF-8");
                String[] uriArr = uri.split("\\?");
                if (uriArr.length > 1) {
                    String[] uriParams = uriArr[1].split("&");
                    for (String uriParam : uriParams) {
                        if (uriParam.startsWith("socketKey=")) {
                            socketKey = uriParam.substring("socketKey=".length());
                        }
                        if (uriParam.startsWith("userId=")) {
                            userId = uriParam.substring("userId=".length());
                        }
                        if (uriParam.startsWith("apiInfo=")) {
                            wsApiInfo = JSON.parseObject(uriParam.substring("apiInfo=".length()));
                            businessSocketKey = wsApiInfo.getString("api");
                        }
                    }
                }
            } catch (Exception e) {
                log.error("创建websocket失败：" + e.getMessage());
            }
        }

        if (StringUtils.isAnyBlank(socketKey, userId)) {
            log.error("websocket鉴权失败！缺少相关参数！");
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
            return;
        }

        if (StrUtils.unequal(ChannelSupervise.socketKeyMap.get(socketKey), userId)) {
            log.error("websocket鉴权失败！");
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
            return;
        }

        ChannelSupervise.socketKeyMap.remove(socketKey);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            log.error("websocket创建链接失败！");
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
            ChannelSupervise.addChannel(ctx.channel());

            if (StringUtils.isBlank(businessSocketKey)) {
                log.error("websocket创建链接失败！业务Key无效！");
                ChannelSupervise.businessChannelMap.put(socketKey, ctx.channel().id());
            } else {
                log.info("websocket创建链接成功！");
                if (!ChannelSupervise.multiBusinessChannelMap.containsKey(businessSocketKey)) {
                    ChannelSupervise.multiBusinessChannelMap.put(businessSocketKey, new ArrayList<>());
                }

                ChannelSupervise.multiBusinessChannelMap.get(businessSocketKey).add(ctx.channel());
            }

        }
    }

    /**
     * 拒绝不合法的请求，并返回错误信息
     */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    /*private String adapterApi(JSONObject wsApiInfo) {
        if (Objects.isNull(wsApiInfo) || wsApiInfo.isEmpty()) {
            return null;
        }

        JSONObject params = new JSONObject();
        switch (wsApiInfo.getString("api")) {
            case "/ws/api/dust/realTimeData":
                params = wsApiInfo.getJSONObject("params");
                return "dust_rtd_" + params.getString("dustCode");
            case "/ws/api/helmet/realTimeData":
                params = wsApiInfo.getJSONObject("params");
                return "helmet_rtd_" + params.getString("helmetProjId");
            case "/ws/api/towerCrane/realTimeData":
                params = wsApiInfo.getJSONObject("params");
                return "towerCrane_rtd_" + params.getString("towerCraneIndex");
            case "/ws/api/elevator/realTimeData":
                params = wsApiInfo.getJSONObject("params");
                return "elevator_rtd_" + params.getString("elevatorIndex");
            case "/ws/api/laborer/realTimeData":
                params = wsApiInfo.getJSONObject("params");
                return "laborer_rtd_" + params.getString("laborerProjId");
            default:
                break;
        }

        return null;
    }*/
}